import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class RemoteNIOCopyServer extends Thread {

	private final int port;
	private final String dest;

	public RemoteNIOCopyServer(int port, String dest) {
		this.port = port;
		this.dest = dest;
	}

	public static void main(String[] args) {
		if (args.length < 2) {
			System.err
					.println("Invalid parameters list. Usage: RemoteNIOCopyServer <port> <dest file>");
			System.exit(1);
		}
		int port = Integer.parseInt(args[0]);
		String dest = args[1];
		RemoteNIOCopyServer server = new RemoteNIOCopyServer(port, dest);
		server.start();
	}

	public void run() {
		try (SocketChannel socket = ServerSocketChannel.open()
				.bind(new InetSocketAddress(port)).accept();
				FileChannel file = FileChannel.open(
						Paths.get(dest),
						StandardOpenOption.CREATE,
						StandardOpenOption.TRUNCATE_EXISTING,
						StandardOpenOption.WRITE);) {
			ByteBuffer bb = ByteBuffer.allocate(100000);
			while (socket.read(bb) != -1) {
				bb.flip();
				file.write(bb);
				bb.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
